<template>
  <div class="btn_warp" style="height:32px;width: 100%;padding-top: 5px;padding-bottom: 10px">
    <el-button type="success" plain class="btn_add" style="width:100px" @click="onAddItem">添加</el-button>
    <el-button type="danger" plain class="btn_delete" style="width: 100px" @click="onDeleteItem">删除</el-button>
    <el-button type="success" style="float: right;margin-right: 30px" @click.prevent="handleSearch">查询</el-button>
    <el-button type="success" style="float: right;margin-right: 5px" @click.prevent="handleClean">全部清空</el-button>
    <el-input v-model="search3" clearable placeholder="按账单状态查询" style="float: right;width: 250px;margin-right: 15px"/>
    <el-input v-model="search2" clearable placeholder="按房产地址查询" style="float: right;width: 250px;margin-right: 15px"/>
    <el-input v-model="search1" clearable placeholder="按日期查询" style="float: right;width: 250px;margin-right: 15px"/>
  </div>
  <el-table @selection-change="handleSelsChange" :data="filterTableData.slice((currentPage-1)*pageSize,currentPage*pageSize)" stripe border style="width:100%" max-height="472" height="472" :cell-style="{ textAlign: 'center' }">
    <el-table-column type="selection" width="40" >
    </el-table-column>
    <el-table-column fixed prop="" label="序号" width="70" :show-overflow-tooltip="true">
      <template #default="scope">
        {{scope.$index+1}}
      </template>
    </el-table-column>
    <el-table-column fixed prop="feeDate" label="日期" width="150" :show-overflow-tooltip="true">
      <template #default="scope">
            <span v-if="scope.row.isUpdate">
              <el-date-picker value-format="YYYY-MM" size="small" style="width: 120px ;" v-model="scope.row.feeDate" type="month" placeholder="选择一个日期"></el-date-picker>
            </span>
        <span v-else>{{ scope.row.feeDate }}</span>
      </template>
    </el-table-column>
    <el-table-column prop="propertyAddress" label="房产地址" width="120" :show-overflow-tooltip="true">
      <template #default="scope">
            <span v-if="scope.row.isUpdate">
              <el-input input-style="height:23px" class="table-input" v-model="scope.row.propertyAddress" maxlength="30" size="large"/>
            </span>
        <span v-else>{{ scope.row.propertyAddress }}</span>
      </template>
    </el-table-column>
    <el-table-column prop="feeStatus" label="账单状态" width="100" :show-overflow-tooltip="true">
      <template #default="scope">
            <span v-if="scope.row.isUpdate">
              <el-select v-model="scope.row.feeStatus" placeholder="选择" size="small">
                <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
              </el-select>
            </span>
        <span v-else>{{ scope.row.feeStatus }}</span>
      </template>
    </el-table-column>
    <el-table-column prop="feeTotal" label="总计应缴(元)" width="120" :show-overflow-tooltip="true">
      <template #default="scope">
<!--            <span v-if="scope.row.isUpdate">
              <el-input input-style="height:23px;" class="table-input" v-model="scope.row.feeTotal" maxlength="30" size="large"/>
            </span>-->
        <span>{{ scope.row.feeTotal }}</span>
      </template>
    </el-table-column>
    <el-table-column prop="waterfee" label="水费(元)" width="120" :show-overflow-tooltip="true">
      <template #default="scope">
<!--            <span v-if="scope.row.isUpdate">
              <el-input input-style="height:23px;" class="table-input" v-model="scope.row.waterfee" maxlength="30" size="large"/>
            </span>-->
        <span>{{ scope.row.waterfee }}</span>
      </template>
    </el-table-column>
    <el-table-column prop="electricityfee" label="电费(元)" width="120" :show-overflow-tooltip="true">
      <template #default="scope">
<!--            <span v-if="scope.row.isUpdate">
              <el-input input-style="height:23px;" class="table-input" v-model="scope.row.electricityfee" maxlength="30" size="large"/>
            </span>-->
        <span>{{ scope.row.electricityfee }}</span>
      </template>
    </el-table-column>
    <el-table-column prop="gasfee" label="气费(元)" width="120" :show-overflow-tooltip="true">
      <template #default="scope">
<!--            <span v-if="scope.row.isUpdate">
              <el-input input-style="height:23px;" class="table-input" v-model="scope.row.gasfee" maxlength="30" size="large"/>
            </span>-->
        <span>{{ scope.row.gasfee }}</span>
      </template>
    </el-table-column>
    <el-table-column prop="feeManagefee" label="管理费用(元)" width="130" :show-overflow-tooltip="true">
      <template #default="scope">
            <span v-if="scope.row.isUpdate">
              <el-input-number input-style="height:23px" :min="0" :max="100000" size="small" controls-position="right" class="table-input" v-model="scope.row.feeManagefee" />
            </span>
        <span v-else>{{ scope.row.feeManagefee }}</span>
      </template>
    </el-table-column>
    <el-table-column prop="feeEnddate" label="缴费截止日期" width="150" :show-overflow-tooltip="true">
      <template #default="scope">
            <span v-if="scope.row.isUpdate">
              <el-date-picker value-format="YYYY-MM-DD" format="YYYY-MM-DD" size="small" style="width: 120px ;" v-model="scope.row.feeEnddate" type="date" placeholder="选择一个日期"></el-date-picker>
            </span>
        <span v-else>{{ scope.row.feeEnddate }}</span>
      </template>
    </el-table-column>
    <el-table-column fixed="right" label="操作" width="265" :show-overflow-tooltip="true">
      <template #default="scope">
        <el-button type="warning" round size="small" @click.prevent="updateRow(scope.$index)">修改</el-button>
        <el-button type="primary" round size="small" @click.prevent="saveRow(scope.$index,scope.row.feeId)">保存</el-button>
        <el-button type="danger" round size="small" @click.prevent="deleteRow(scope.row.feeId)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>
  <div class="page_warp">
    <el-pagination  background @current-change="handleCurrentChange" v-model:page-size="pageSize" v-model:current-page="currentPage" layout="prev, pager, next , jumper" :total="filterTableData.length"></el-pagination>
  </div>
</template>

<script>
import { ElMessage,ElMessageBox } from 'element-plus'
import {ref, onMounted} from 'vue'
import {nanoid} from 'nanoid'
import axios from "axios";
import {useRouter} from 'vue-router'
export default {
  name: "HouseHold",
  setup(){
    const tableSels=ref([])
    const tableData = ref([])
    const pageSize=ref(10)
    const currentPage=ref(1)
    const router=useRouter()
    const statusOptions=[
      {
        value:'未缴清',
        label:'未缴清'
      },
      {
        value:'已逾期',
        label:'已逾期'
      },
      {
        value:'已缴清',
        label:'已缴清'
      }
    ]
    const search1=ref('')
    const search2=ref('')
    const search3=ref('')
    //条件过滤
    let filterTableData =ref([])

    //按条件进行查询
    function handleSearch(){
      filterTableData.value=tableData.value.filter(
          (data) => data.feeDate.toLowerCase().includes(search1.value.toLowerCase()) //匹配账单日期
              && data.propertyAddress.toLowerCase().includes(search2.value.toLowerCase()) //匹配房产地址
              && data.feeStatus.toLowerCase().includes(search3.value.toLowerCase()) //匹配账单状态
      )
    }
    //清空查询条件
    function handleClean(){
      search1.value=''
      search2.value=''
      search3.value=''
    }
    //选择添加事件
    function onAddItem(){
      tableData.value.push({
        feeId:nanoid(),   //账单id
        feeForeignkey:'',  //房产编号
        feeDate: formatDate1(new Date()),  //账单日期
        feeEnddate: formatDate2(new Date()),  //截止日期
        feeStatus: '未缴清',  //账单状态
        feeWaterid: '',  //水费id
        feeElectricityid: '',  //电费id
        feeGasid: '',  //气费id
        feeManagefee: 200,  //管理费用
        feeTotal: '',  //总计应缴
        propertyAddress: '',  //房产地址
        waterfee: '',  //水费
        electricityfee: '',  //电费
        gasfee: '',  //气费
        isUpdate:true,    //是否为编辑状态
        isAdd:true,    //是否为新增状态
      },)
      currentPage.value=Math.ceil(tableData.value.length/pageSize.value)
    }
    //选择删除事件
    function onDeleteItem(){
      ElMessageBox.confirm('确认删除此记录吗？', '警告', {confirmButtonText: '确认', cancelButtonText: '取消', type: 'warning',}).then(() => {
        tableSels.value.forEach((tableSel)=>{
          tableData.value.forEach((item,index)=>{
            if(item===tableSel){
              tableData.value.splice(index,1)
              //发送请求进行数据删除
              axios.get('http://localhost:8085/deleteFee',{
                params:{
                  feeId:item.feeId,
                }
              }).then(
                  ()=>{
                    ElMessage({type:'success',message:'删除成功！'})
                  },
                  ()=>{
                    ElMessage({type:'error',message:'删除失败！'})
                    setTimeout(()=>{
                      router.go(0)
                    },500)
                  }
              )
            }
          })
        })
      }).catch(() => {
        ElMessage({type: 'info', message: '删除失败！',})
      })
    }
    //行修改事件
    function updateRow(index) {
      filterTableData.value[pageSize.value * (currentPage.value - 1) + index].isUpdate = true
    }
    //行保存事件
    function saveRow(index){
      let FeeObj=filterTableData.value[pageSize.value*(currentPage.value-1)+index]
      if(!FeeObj.isUpdate){
        ElMessage({message:'没有数据需要保存！'})
      }else if(FeeObj.feeDate === ''){  //判断
        ElMessage({message:'日期不能为空！'})
      }else if(FeeObj.propertyAddress === ''){
        ElMessage({message:'物业地址不能为空！'})
      }else if(FeeObj.isAdd){
        if(isRepeat(FeeObj,index)) return
        axios.all([
          axios.get("http://localhost:8085/getWaterfee", {params:{feeDate:FeeObj.feeDate, propertyAddress: FeeObj.propertyAddress}}),
          axios.get("http://localhost:8085/getElectricityfee", {params:{feeDate:FeeObj.feeDate, propertyAddress: FeeObj.propertyAddress}}),
          axios.get("http://localhost:8085/getGasfee", {params:{feeDate:FeeObj.feeDate, propertyAddress: FeeObj.propertyAddress}})
        ]).then(
            (resp)=>{
              resp.forEach((item,index)=>{
                if(index==0){
                  FeeObj.waterfee=item.data
                }else if(index==1){
                  FeeObj.electricityfee=item.data
                }else{
                  FeeObj.gasfee=item.data
                }
              })
              FeeObj.feeTotal=parseInt(FeeObj.waterfee)+parseInt(FeeObj.electricityfee)+parseInt(FeeObj.gasfee+FeeObj.feeManagefee)
              axios.get("http://localhost:8085/addFee", {
                params:{
                  feeId:FeeObj.feeId,
                  feeForeignkey:FeeObj.feeForeignkey,
                  feeDate:FeeObj.feeDate,
                  feeEnddate:FeeObj.feeEnddate,
                  feeStatus:FeeObj.feeStatus,
                  feeWaterid:FeeObj.feeWaterid,
                  feeElectricityid:FeeObj.feeElectricityid,
                  feeGasid:FeeObj.feeGasid,
                  feeManagefee:FeeObj.feeManagefee,
                  feeTotal:FeeObj.feeTotal,
                  propertyAddress:FeeObj.propertyAddress,
                  waterfee:FeeObj.waterfee,
                  electricityfee:FeeObj.electricityfee,
                  gasfee:FeeObj.gasfee
                }
              }).then(
                  ()=>{
                    ElMessage({type: 'success',message:'保存成功！'})
                    FeeObj.isUpdate=false
                    FeeObj.isAdd=false
                  },
                  ()=>{
                    ElMessage({type: 'success',message:'保存失败！'})
                  }
              )
            },
            ()=>{
              ElMessage({type: 'error',message:'未查询到相关月份的水、电、气费账单！'})
            }
        )
      }else{
        if(isRepeat(FeeObj,index)) return
        axios.all([
          axios.get("http://localhost:8085/getWaterfee", {params:{feeDate:FeeObj.feeDate, propertyAddress: FeeObj.propertyAddress}}),
          axios.get("http://localhost:8085/getElectricityfee", {params:{feeDate:FeeObj.feeDate, propertyAddress: FeeObj.propertyAddress}}),
          axios.get("http://localhost:8085/getGasfee", {params:{feeDate:FeeObj.feeDate, propertyAddress: FeeObj.propertyAddress}})
        ]).then(
            (resp)=>{
              resp.forEach((item,index)=>{
                if(index==0){
                  FeeObj.waterfee=item.data
                }else if(index==1){
                  FeeObj.electricityfee=item.data
                }else{
                  FeeObj.gasfee=item.data
                }
              })
              FeeObj.feeTotal=parseInt(FeeObj.waterfee)+parseInt(FeeObj.electricityfee)+parseInt(FeeObj.gasfee+FeeObj.feeManagefee)
              axios.get("http://localhost:8085/updateFee", {
                params:{
                  feeId:FeeObj.feeId,
                  feeForeignkey:FeeObj.feeForeignkey,
                  feeDate:FeeObj.feeDate,
                  feeEnddate:FeeObj.feeEnddate,
                  feeStatus:FeeObj.feeStatus,
                  feeWaterid:FeeObj.feeWaterid,
                  feeElectricityid:FeeObj.feeElectricityid,
                  feeGasid:FeeObj.feeGasid,
                  feeManagefee:FeeObj.feeManagefee,
                  feeTotal:FeeObj.feeTotal,
                  propertyAddress:FeeObj.propertyAddress,
                  waterfee:FeeObj.waterfee,
                  electricityfee:FeeObj.electricityfee,
                  gasfee:FeeObj.gasfee
                }
              }).then(
                  ()=>{
                    ElMessage({type: 'success',message:'保存成功！'})
                    FeeObj.isUpdate=false
                  },
                  ()=>{
                    ElMessage({type: 'success',message:'保存失败！'})
                  }
              )
            },
            ()=>{
              ElMessage({type: 'error',message:'网络请求失败！'})
            }
        )
      }
    }
    //行删除事件
    function deleteRow(feeId){
      ElMessageBox.confirm('确认删除此记录吗？', '警告', {confirmButtonText: '确认', cancelButtonText: '取消', type: 'warning',}).then(() => {
        tableData.value.forEach((item,index)=>{
          if(item.feeId===feeId){
            axios.get('http://localhost:8085/deleteFee',{
              params:{
                feeId:item.feeId,   //报修id
              }
            }).then(
                ()=>{
                  ElMessage({type:'success',message:'删除成功！'})
                  tableData.value.splice(index,1)
                },
                ()=>{
                  ElMessage({type:'error',message:'删除失败！'})
                }
            )
          }
        })
      }).catch(() => {
        ElMessage({type: 'info', message: '删除失败！',})
      })
    }
    //分页事件
    function handleCurrentChange(value){
      currentPage.value = value;
    }
    //处理多选
    const handleSelsChange=(sels)=>{
      tableSels.value=sels
    }
    //挂载加载数据
    onMounted(()=>{
      axios.get('http://localhost:8085/getFee').then(
          (response)=>{
            tableData.value=response.data
            filterTableData.value=response.data
          },
          ()=>{
          }
      )
    })
    //自定义生成的时间格式化
    function formatDate1(val) {
      if(isNaN(val)) return ''
      const date = new Date(Number(val)); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
      const Y = date.getFullYear() + "-";
      const M = (date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1);
      // const D = date.getDate() + " ";
      // const h = date.getHours() + ":";
      // const m = date.getMinutes() + ":";
      // const s = (date.getSeconds() < 10 ? "0" + (date.getSeconds()) : date.getSeconds());
      return Y + M;
    }
    function formatDate2(val) {
      if(isNaN(val)) return ''
      const date = new Date(Number(val)); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
      const Y = date.getFullYear() + "-";
      const M = (date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1)+"-";
      const D = date.getDate() + " ";
      // const h = date.getHours() + ":";
      // const m = date.getMinutes() + ":";
      // const s = (date.getSeconds() < 10 ? "0" + (date.getSeconds()) : date.getSeconds());
      return Y + M+D;
    }
    //判断记录是否重复
    function isRepeat(Obj,index){
      let tip=0
      tableData.value.forEach((item,indexx)=>{
        if(Obj.propertyAddress==item.propertyAddress && Obj.feeDate == item.feeDate && (pageSize.value*(currentPage.value-1)+index)!=indexx){
          tip=1
        }
      })
      if(tip==1){
        ElMessage({type:'error',message:'保存失败,该账单信息记录已存在！'})
        return true
      }else{
        return false
      }
    }

    return{
      tableSels,
      tableData,
      filterTableData,
      search1,
      search2,
      search3,
      pageSize,
      currentPage,
      formatDate1,
      formatDate2,
      onAddItem,
      onDeleteItem,
      updateRow,
      saveRow,
      deleteRow,
      handleCurrentChange,
      handleSelsChange,
      statusOptions,
      isRepeat,
      handleSearch,
      handleClean
    }
  }
}
</script>

<style scoped>
  .el-table{
    /*padding: 20px 20px 20px 20px;*/
  }
  .page_warp{
    width: 600px;
    margin: 5px auto;
    height: 40px;
  }
  .el-pagination{
    margin-right: 50px;
  }
  .demo-date-picker {
    display: flex;
    width: 100%;
    padding: 0;
    flex-wrap: wrap;
  }

  .demo-date-picker .block {
    padding: 30px 0;
    text-align: center;
    border-right: solid 1px var(--el-border-color-base);
    flex: 1;
  }
  .demo-date-picker .block:last-child {
    border-right: none;
  }
  .demo-date-picker .demonstration {
    display: block;
    color: var(--el-text-color-secondary);
    font-size: 14px;
    margin-bottom: 20px;
  }
  .el-input-number--small{
    width: 100px;
  }
</style>